<!--
  * 实训室耗材申请
  *
  * @Author:    李韵妍
  * @Date:      2024-11-08 13:31:04
  * @Copyright  🐂🐎bloc
-->
<template>
    <!---------- 查询表单form begin ----------->
    <a-form class="smart-query-form">
        <a-row class="smart-query-form-row">
            <a-form-item class="smart-query-form-item">
                <a-button type="primary" @click="onSearch">
                    <template #icon>
                        <SearchOutlined />
                    </template>
                    查询
                </a-button>
                <a-button @click="resetQuery" class="smart-margin-left10">
                    <template #icon>
                        <ReloadOutlined />
                    </template>
                    重置
                </a-button>
            </a-form-item>
        </a-row>
    </a-form>
    <!---------- 查询表单form end ----------->

    <a-card size="small" :bordered="false" :hoverable="true">
        <!---------- 表格操作行 begin ----------->
        <a-row class="smart-table-btn-block">
            <div class="smart-table-operate-block">
                <a-button @click="showForm" type="primary" size="small">
                    <template #icon>
                        <PlusOutlined />
                    </template>
                    新建
                </a-button>
                <a-button @click="confirmBatchDelete" type="primary" danger size="small" :disabled="selectedRowKeyList.length == 0">
                    <template #icon>
                        <DeleteOutlined />
                    </template>
                    批量删除
                </a-button>
            </div>
            <div class="smart-table-setting-block">
                <TableOperator v-model="columns" :tableId="null" :refresh="queryData" />
            </div>
        </a-row>
        <!---------- 表格操作行 end ----------->

        <!---------- 表格 begin ----------->
        <a-table
            size="small"
            :dataSource="tableData"
            :columns="columns"
            :scroll="{ x: 1900 }"
            rowKey="id"
            bordered
            :loading="tableLoading"
            :pagination="false"
            :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
        >
            <template #bodyCell="{ text, record, column }">

              <template v-if="column.dataIndex === 'applicant'">
                {{record.actualName}}
              </template>
              <template v-if="column.dataIndex === 'guideTeacherSignature'||column.dataIndex === 'adminSignature'">
                <a-tag :color="text == 0? 'cyan' : text == 1? 'green' :  'orange'">
                  {{ text == 0? '审核中' : text == 1? '已通过' :  '不通过'}}
                </a-tag>
              </template>
              <template v-if="column.dataIndex === 'returnStatus'">
                <a-tag :color="text == 0? 'orange' :'cyan'">
                  {{ text == 0? '未归还' : '已归还' }}
                </a-tag>
              </template>
              <template v-if="column.dataIndex === 'returnConfirmation'">
                <a-tag :color="text == 0? 'orange' :'cyan'  ">
                  {{ text == 0? '未确认' : '已确认' }}
                </a-tag>
              </template>


                <template v-if="column.dataIndex === 'action'">
                    <div class="smart-table-operate">
                        <a-button @click="showForm(record)" type="link">编辑</a-button>
                        <a-button @click="onDelete(record)" danger type="link" v-if="record.adminSignature ==0 && record.guideTeacherSignature == 0">删除</a-button>
                        <a-button @click="showApprovalFrom(record)" type="link" v-if="record.returnStatus!=1 || record.returnConfirmation!=1">{{record.returnStatus == 0 ? '审批' : '归还审批' }}</a-button>
                        <a-button @click="onReturn(record)" type="link" v-if="record.applicant == UserStore.employeeId && record.adminSignature == 1 && record.returnFileId==null">归还</a-button>
                    </div>
                </template>
            </template>
        </a-table>
        <!---------- 表格 end ----------->

        <div class="smart-query-table-page">
            <a-pagination
                showSizeChanger
                showQuickJumper
                show-less-items
                :pageSizeOptions="PAGE_SIZE_OPTIONS"
                :defaultPageSize="queryForm.pageSize"
                v-model:current="queryForm.pageNum"
                v-model:pageSize="queryForm.pageSize"
                :total="total"
                @change="queryData"
                @showSizeChange="queryData"
                :show-total="(total) => `共${total}条`"
            />
        </div>

          <EquipmentBorrowApplicationForm  ref="formRef" @reloadList="queryData"/>
          <EquipmentBorrowApplicationApprovalForm  ref="approvalFormRef" @reloadList="queryData"/>
          <a-modal v-model:open="uploadModalFlag" title="上传文件" @onCancel="hideUploadModal" @ok="UploadModal">
            <FilePreviewModal ref="filePreviewModalRef" />
            <FileUpload
            list-type="text"
            :maxUploadSize="1"
            buttonText="点击上传文件"
            :defaultFileList="[]"
            :multiple="true"
            :folder="FILE_FOLDER_TYPE_ENUM.COMMON.value"
            @change="onUploadSuccess"
            />
          </a-modal>
          <a-modal v-model:open="returnFormRef" title="归还审批" @onCancel="hideReturnModal" @ok="returnModal">
            <FilePreviewModal ref="filePreviewModalRef"  :style="{width:'400px',height:'400px'}"/>
          </a-modal>
    </a-card>
</template>
<script setup>
    import { reactive, ref, onMounted } from 'vue';
    import { message, Modal } from 'ant-design-vue';
    import { SmartLoading } from '/@/components/framework/smart-loading';
    import { equipmentBorrowApplicationApi } from '/@/api/business/equipment-borrow-application/equipment-borrow-application-api';
    import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
    import { smartSentry } from '/@/lib/smart-sentry';
    import TableOperator from '/@/components/support/table-operator/index.vue';
    import EquipmentBorrowApplicationForm from './equipment-borrow-application-form.vue';
    import EquipmentBorrowApplicationApprovalForm from './equipment-borrow-application-approval-from.vue';
    import {useUserStore} from "/@/store/modules/system/user.js";
    import {FILE_FOLDER_TYPE_ENUM} from "/@/constants/support/file-const.js";
    import FilePreviewModal from '/@/components/support/file-preview-modal/index.vue';
    import FileUpload from '/@/components/support/file-upload/index.vue';
    //import FilePreview from '/@/components/support/file-preview/index.vue'; // 图片预览组件
    import { fileApi } from '/@/api/support/file-api';
    // ---------------------------- 数据----------------------------
    // 选中行的key列表
   const UserStore =  useUserStore()
    const returnId = ref();
    // ---------------------------- 表格列 ----------------------------

    const columns = ref([
        {
        title:'序号',
        customRender: ({text, record, index}) => {
          return `${(queryForm.pageNum - 1) * queryForm.pageSize + Number(index) + 1}`
        }},
        {
            title: '借用理由',
            dataIndex: 'borrowReason',
            ellipsis: false,
        },
        {
            title: '申请人姓名',
            dataIndex: 'applicant',
            ellipsis: false,
        },
        {
            title: '申请班级',
            dataIndex: 'classroom',
            ellipsis: false,
        },
        {
            title: '开始日期',
            dataIndex: 'borrowStartDate',
            ellipsis: false,
        },
        {
            title: '结束日期',
            dataIndex: 'borrowEndDate',
            ellipsis: false,
        },
        {
            title: '设备名称',
            dataIndex: 'equipmentName',
            ellipsis: false,
        },
        {
            title: '规格型号',
            dataIndex: 'specificationModel',
            ellipsis: false,
        },
        // {
        //     title: '数量',
        //     dataIndex: 'quantity',
        //     ellipsis: false,
        // },
        // {
        //     title: '设备当前状态',
        //     dataIndex: 'borrowStatus',
        //     ellipsis: false,
        // },
        {
            title: '备注',
            dataIndex: 'remark',
            ellipsis: false,
        },
        {
            title: '指导老师审批',
            dataIndex: 'guideTeacherSignature',
            ellipsis: false,
        },
        {
            title: '管理员审批',
            dataIndex: 'adminSignature',
            ellipsis: false,
        },
        {
            title: '借出日期',
            dataIndex: 'borrowDate',
            ellipsis: false,
        },

        {
            title: '归还日期',
            dataIndex: 'returnDate',
            ellipsis: false,
        },
        {
            title: '归还状态',
            dataIndex: 'returnStatus',
            ellipsis: false,
        },
      {
        title: '确认归还',
        dataIndex: 'returnConfirmation',
        ellipsis: false,
      },

        {
            title: '操作',
            dataIndex: 'action',
            fixed: 'right',
            width:160,
        },
    ]);

    // ---------------------------- 查询数据表单和方法 ----------------------------

    const queryFormState = {
        pageNum: 1,
        pageSize: 10,
    };
    // 查询表单form
    const queryForm = reactive({ ...queryFormState });
    // 表格加载loading
    const tableLoading = ref(false);
    // 表格数据
    const tableData = ref([]);
    // 总数
    const total = ref(0);
    //文件上传
    const uploadModalFlag = ref(false);
    //文件查看
    const filePreviewModalRef = ref();
    //文件列表
    const fileList = ref([]);


    // 重置查询条件
    function resetQuery() {
        let pageSize = queryForm.pageSize;
        Object.assign(queryForm, queryFormState);
        queryForm.pageSize = pageSize;
        queryData();
    }

    // 搜索
    function onSearch(){
      queryForm.pageNum = 1;
      queryData();
    }

    // 查询数据
    async function queryData() {
        tableLoading.value = true;
        try {
            let queryResult = await equipmentBorrowApplicationApi.queryPage(queryForm);
            tableData.value = queryResult.data.list;
            total.value = queryResult.data.total;
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
            tableLoading.value = false;
        }
    }


    onMounted(queryData);

    // ---------------------------- 添加/修改 ----------------------------
    const formRef = ref();

    const approvalFormRef = ref();

    const returnFormRef = ref();

    const ApprovalReturnId = ref();

    function showForm(data) {
        formRef.value.show(data);
    }

   async function showApprovalFrom(data){
      if(data.returnStatus == 0){
        approvalFormRef.value.show(data);
      }else{
        returnFormRef.value = true;
        ApprovalReturnId.value = data.id;
        await fileApi.getFileById(data.returnFileId).then((res)=>{
          view(res.data)
        })

      }

    }

    const hideReturnModal = () => {
      returnFormRef.value = false;
    };

    const returnModal = () => {
      equipmentBorrowApplicationApi.returnApproval(ApprovalReturnId.value).then((res)=>{
        message.success('操作成功');
        queryData();
      })
      returnFormRef.value = false;
    };

    // ---------------------------- 单个删除 ----------------------------
    //确认删除
    function onDelete(data){
        Modal.confirm({
            title: '提示',
            content: '确定要删除选吗?',
            okText: '删除',
            okType: 'danger',
            onOk() {
                requestDelete(data);
            },
            cancelText: '取消',
            onCancel() {},
        });
    }
    //请求归还
    async function onReturn(data){
      returnId.value = data.id;
      uploadModalFlag.value = true;



    }
    function hideUploadModal() {
      uploadModalFlag.value = false;
    }

  async  function UploadModal() {

    SmartLoading.show();
    try {
         let form = {
           returnFileId:fileList.value[0].fileId,
           id:returnId.value,
         }
         await  equipmentBorrowApplicationApi.returnEquipment(form)

      message.success('归还成功');
      queryData();
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
      uploadModalFlag.value = false;
    }
    }

    function onUploadSuccess(value){
      fileList.value = [...value]
    }

    function view(file) {
      filePreviewModalRef.value.showPreview(file);
    }

    //请求删除
    async function requestDelete(data){
        SmartLoading.show();
        try {
            let deleteForm = {
                goodsIdList: selectedRowKeyList.value,
            };
            await equipmentBorrowApplicationApi.delete(data.id);
            message.success('删除成功');
            queryData();
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
            SmartLoading.hide();
        }
    }

    // ---------------------------- 批量删除 ----------------------------

    // 选择表格行
    const selectedRowKeyList = ref([]);

    function onSelectChange(selectedRowKeys) {
        selectedRowKeyList.value = selectedRowKeys;
    }

    // 批量删除
    function confirmBatchDelete() {
        Modal.confirm({
            title: '提示',
            content: '确定要批量删除这些数据吗?',
            okText: '删除',
            okType: 'danger',
            onOk() {
                requestBatchDelete();
            },
            cancelText: '取消',
            onCancel() {},
        });
    }

    //请求批量删除
    async function requestBatchDelete() {
        try {
            SmartLoading.show();
            await equipmentBorrowApplicationApi.batchDelete(selectedRowKeyList.value);
            message.success('删除成功');
            queryData();
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
            SmartLoading.hide();
        }
    }
</script>
